package com.cloudkinto.service.fbaorderinput.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.OrderCodeUtil;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.fbaorderinput.FbaOrderInputService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.fbaorderinput.vo.*;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.storage.StorageService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author zhangyy
 * @since 2020-08-20
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class FbaOrderInputServiceImpl extends ServiceImpl<FbaOrderInputDao, FbaOrderInputDo> implements FbaOrderInputService {
    @Autowired
    private FbaOrderInputDao dao;
    @Autowired
    private StorageService storageService;
    @Autowired
    private FbaOrderInputPackageDao fbaOrderInputPackageDao;
    @Autowired
    private FbaOrderInputProductDao fbaOrderInputProductDao;
    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private OrderOutputService orderOutputService;
    @Autowired
    private FbaStorageDao fbaStorageDao;
    @Autowired
    private CompanyDao companyDao;

    @Override
    public SingleResult addInit() {
        Map result = new HashMap();

        List<Map> storageChinaList = new ArrayList<>();
        List<Map> storageJapanList = new ArrayList<>();
        List<StorageDo> storageDoList = storageDao.selectList(null);
        if (!CollectionUtils.isEmpty(storageDoList)) {
            storageDoList.forEach(storageDo -> {
                Map map = new HashMap();
                map.put("id", storageDo.getId());
                map.put("value", storageDo.getStorageName());
                if (storageDo.getCountryType() == 1) {
                    storageJapanList.add(map);
                } else if (storageDo.getCountryType() == 2) {
                    storageChinaList.add(map);
                }
            });
        }
        result.put("storageChinaList", storageChinaList);
        result.put("storageJapanList", storageJapanList);


        List<Map> sendTypeList = new ArrayList<>();
        LambdaQueryWrapper<DicBusinessItemDo> dicBusinessItemDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dicBusinessItemDoLambdaQueryWrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.fbaOrderInputSendType);
        List<DicBusinessItemDo> businessItemDoList = dicBusinessItemDao.selectList(dicBusinessItemDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(businessItemDoList)) {
            businessItemDoList.forEach(dicBusinessItemDo -> {
                Map map = new HashMap();
                map.put("id", dicBusinessItemDo.getId());
                map.put("value", dicBusinessItemDo.getDicItemValue());
                sendTypeList.add(map);
            });
        }
        result.put("sendTypeList", sendTypeList);


        List<Map> statusList = new ArrayList<>();
        LambdaQueryWrapper<DicBusinessItemDo> statusLambdaQueryWrapper = new LambdaQueryWrapper<>();
        statusLambdaQueryWrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.fbaOrderInputStatus);
        List<DicBusinessItemDo> statusItemDoList = dicBusinessItemDao.selectList(statusLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(statusItemDoList)) {
            statusItemDoList.forEach(dicBusinessItemDo -> {
                Map map = new HashMap();
                map.put("id", dicBusinessItemDo.getId());
                map.put("value", dicBusinessItemDo.getDicItemValue());
                statusList.add(map);
            });
        }
        result.put("statusList", statusList);

        return SingleResult.success(result);
    }

    @Override
    public FbaOrderInputAddReq add(FbaOrderInputAddReq req, Long userId, Long companyId) {
        if (companyId == null) {
            throw new BizException(SysConstant.Error_Company);
        }
        FbaOrderInputDo entityDo = new FbaOrderInputDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        entityDo.setCompanyId(companyId);
        dao.insert(entityDo);

        String fbaOrderInputNumber = OrderCodeUtil.getFbaOrderInputNumber(entityDo.getId());
        entityDo.setFbaOrderNumber(fbaOrderInputNumber);
        dao.updateById(entityDo);

        req.getPackageAddList().forEach(fbaOrderInputPackageAdd -> {
            FbaOrderInputPackageDo fbaOrderInputPackageDo = new FbaOrderInputPackageDo();
            BeanUtils.copyProperties(fbaOrderInputPackageAdd,fbaOrderInputPackageDo);
            fbaOrderInputPackageDo.setFbaOrderInputId(entityDo.getId());
            fbaOrderInputPackageDao.insert(fbaOrderInputPackageDo);

            fbaOrderInputPackageAdd.getProductAddList().forEach(fbaOrderInputProductAdd -> {
                FbaOrderInputProductDo fbaOrderInputProductDo = new FbaOrderInputProductDo();
                BeanUtils.copyProperties(fbaOrderInputProductAdd,fbaOrderInputProductDo);
                fbaOrderInputProductDo.setFbaOrderInputId(entityDo.getId());
                fbaOrderInputProductDo.setFbaOrderInputPackageId(fbaOrderInputPackageDo.getId());
                fbaOrderInputProductDao.insert(fbaOrderInputProductDo);
            });
        });

        return null;
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(FbaOrderInputDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(FbaOrderInputDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        Map result = (Map) addInit().getData();

        result.put("detail", detail(id));
        return SingleResult.success(result);
    }

    @Override
    public FbaOrderInputUpdateReq update(FbaOrderInputUpdateReq req, Long userId) {
        FbaOrderInputDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);

        LambdaQueryWrapper<FbaOrderInputPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(FbaOrderInputPackageDo::getFbaOrderInputId,req.getId());
        fbaOrderInputPackageDao.delete(packageDoLambdaQueryWrapper);

        LambdaQueryWrapper<FbaOrderInputProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productDoLambdaQueryWrapper.eq(FbaOrderInputProductDo::getFbaOrderInputId,req.getId());
        fbaOrderInputProductDao.delete(productDoLambdaQueryWrapper);

        req.getPackageAddList().forEach(fbaOrderInputPackageAdd -> {
            FbaOrderInputPackageDo fbaOrderInputPackageDo = new FbaOrderInputPackageDo();
            BeanUtils.copyProperties(fbaOrderInputPackageAdd,fbaOrderInputPackageDo);
            fbaOrderInputPackageDo.setFbaOrderInputId(entityDo.getId());
            fbaOrderInputPackageDao.insert(fbaOrderInputPackageDo);

            fbaOrderInputPackageAdd.getProductAddList().forEach(fbaOrderInputProductAdd -> {
                FbaOrderInputProductDo fbaOrderInputProductDo = new FbaOrderInputProductDo();
                BeanUtils.copyProperties(fbaOrderInputProductAdd,fbaOrderInputProductDo);
                fbaOrderInputProductDo.setFbaOrderInputId(entityDo.getId());
                fbaOrderInputProductDo.setFbaOrderInputPackageId(fbaOrderInputPackageDo.getId());
                fbaOrderInputProductDao.insert(fbaOrderInputProductDo);
            });
        });

        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(FbaOrderInputDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(FbaOrderInputDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        FbaOrderInputDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        dao.updateById(entityDo);
        dao.deleteById(id);

        LambdaQueryWrapper<FbaOrderInputPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(FbaOrderInputPackageDo::getFbaOrderInputId,id);
        fbaOrderInputPackageDao.delete(packageDoLambdaQueryWrapper);

        LambdaQueryWrapper<FbaOrderInputProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productDoLambdaQueryWrapper.eq(FbaOrderInputProductDo::getFbaOrderInputId,id);
        fbaOrderInputProductDao.delete(productDoLambdaQueryWrapper);

        return 1;
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(FbaOrderInputDo entityDo, Long userId) {
        entityDo.setDeleteBy(userId);
        entityDo.setDeleteTime(new Date());
    }

    @Override
    public FbaOrderInputDetailReq detail(Long id) {
        FbaOrderInputDo entityDo = dao.selectById(id);
        FbaOrderInputDetailReq res = new FbaOrderInputDetailReq();
        res.setCompanyId(entityDo.getCompanyId());
        BeanUtils.copyProperties(entityDo, res);

        List<FbaOrderInputDetailPackage> packageList = new ArrayList<>();

        LambdaQueryWrapper<FbaOrderInputPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(FbaOrderInputPackageDo::getFbaOrderInputId,id);
        List<FbaOrderInputPackageDo> fbaOrderInputPackageDos = fbaOrderInputPackageDao.selectList(packageDoLambdaQueryWrapper);
        if(!CollectionUtils.isEmpty(fbaOrderInputPackageDos)){
            fbaOrderInputPackageDos.forEach(fbaOrderInputPackageDo -> {
                FbaOrderInputDetailPackage detailPackage = new FbaOrderInputDetailPackage();
                BeanUtils.copyProperties(fbaOrderInputPackageDo,detailPackage);

                List<FbaOrderInputDetailProduct> productList = new ArrayList<>();
                LambdaQueryWrapper<FbaOrderInputProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productDoLambdaQueryWrapper.eq(FbaOrderInputProductDo::getFbaOrderInputPackageId,fbaOrderInputPackageDo.getFbaOrderInputId());
                List<FbaOrderInputProductDo> fbaOrderInputProductDos = fbaOrderInputProductDao.selectList(productDoLambdaQueryWrapper);
                if(!CollectionUtils.isEmpty(fbaOrderInputProductDos)){
                    fbaOrderInputProductDos.forEach(fbaOrderInputProductDo -> {
                        FbaOrderInputDetailProduct product = new FbaOrderInputDetailProduct();
                        BeanUtils.copyProperties(fbaOrderInputProductDo,product);
                        ProductInfoDo productInfoDo = productInfoDao.selectById(fbaOrderInputProductDo.getProductId());
                        if(productInfoDo!=null){
                            product.setSku(productInfoDo.getCommoditySku());
                            product.setProductName(productInfoDo.getProductName());
                        }
                        productList.add(product);
                    });
                }
                detailPackage.setProductList(productList);

                packageList.add(detailPackage);
            });
        }

        res.setPackageList(packageList);
        return res;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return addInit();
    }

    @Override
    public List<FbaOrderInputListPageRes> getList(Map<String, String> map) {
        QueryWrapper<FbaOrderInputDo> wrapper = queryBuild(map);
        List<FbaOrderInputDo> list = this.list(wrapper);
        List<FbaOrderInputListPageRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<FbaOrderInputDo> wrapper = queryBuild(map);
        IPage<FbaOrderInputDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<FbaOrderInputListPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    @Override
    public SingleResult fbaReturnInit(Long id, Long userId) {
        FbaOrderInputDo fbaOrderInputDo = dao.selectById(id);

        Map result = (Map) orderOutputService.addInit(userId, fbaOrderInputDo.getCompanyId()).getData();
        result.put("storage", storageService.getList(new HashMap<>()));

        result.putAll((Map) addInit().getData());

        result.put("detail",detail(id));
        return SingleResult.success(result);
    }

    //查询分页列表之后对列表数据的处理
    private List<FbaOrderInputListPageRes> handlerListAfter(List<FbaOrderInputDo> list) {
        List<FbaOrderInputListPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(fbaOrderInputDo -> {
                FbaOrderInputListPageRes res = new FbaOrderInputListPageRes();
                res.setFbaOrderNumber(fbaOrderInputDo.getFbaOrderNumber());
                StorageDo storageDoCh = storageDao.selectById(fbaOrderInputDo.getStorageChina());
                if (storageDoCh != null) {
                    res.setStorageChina(storageDoCh.getStorageName());
                }
                StorageDo storageDoJa = storageDao.selectById(fbaOrderInputDo.getStorageJapan());
                if (storageDoJa != null) {
                    res.setStorageJapan(storageDoJa.getStorageName());
                }
                DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(fbaOrderInputDo.getSendType());
                if (businessItemDo != null) {
                    res.setSendType(businessItemDo.getDicItemValue());
                }
                if (fbaOrderInputDo.getClearance() == 1) {
                    res.setClearance("退税报关");
                } else if (fbaOrderInputDo.getClearance() == 2) {
                    res.setClearance("非退税");
                }

                CompanyDo companyDo = companyDao.selectById(fbaOrderInputDo.getCompanyId());
                if(companyDo != null){
                    res.setCompanyCode(companyDo.getCompanyCode());
                }


                res.setIsInsurance(fbaOrderInputDo.getIsInsurance() == 0 ? "否" : "是");
                res.setCoverage(fbaOrderInputDo.getCoverage());
                res.setIsCloudkinto(fbaOrderInputDo.getIsCloudkinto() == 0 ? "否" : "是");
                res.setFbaProcedure(fbaOrderInputDo.getFbaProcedure() == 1 ? "海运订单" : "空运订单");

                DicBusinessItemDo status = dicBusinessItemDao.selectById(fbaOrderInputDo.getStatus());
                if (status != null) {
                    res.setStatus(status.getDicItemValue());
                }
                result.add(res);
            });
        }
        return result;
    }

    private IPage<FbaOrderInputDo> pageInit(Map<String, String> map) {
        IPage<FbaOrderInputDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<FbaOrderInputDo> queryBuild(Map<String, String> map) {
        QueryWrapper<FbaOrderInputDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("fba_order_number", map.get("keyword"));
        }
        return wrapper;
    }


}
